package com.sfj.system.service.task;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kaka.starter.token.util.HeaderUtils;
import com.sfj.common.exception.CheckException;
import com.sfj.system.dto.task.*;
import com.sfj.system.entity.TaskEntity;
import com.sfj.system.entity.TaskProblemEntity;
import com.sfj.system.enums.OrgEnum;
import com.sfj.system.enums.ProblemTypeEnum;
import com.sfj.system.mapper.TaskMapper;
import com.sfj.system.service.UploadService;
import com.sfj.system.service.group.GroupService;
import com.sfj.system.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kaka
 * @Date 2025/07/01
 */
@Service
public class TaskQueryService {

    @Resource
    private TaskMapper taskMapper;

    @Autowired
    private ProblemService problemService;
    @Autowired
    private GroupService groupService;
    @Autowired
    private UploadService uploadService;

    //首页数据统计
    public TaskTotalDTO getTaskStatistics() {
        return taskMapper.getTaskStatistics();
    }

    public IPage<TaskEntity> queryTaskListByPage(TaskQueryDTO taskQueryDTO) {
        Page<TaskEntity> page = new Page<>(taskQueryDTO.getPageNo(), taskQueryDTO.getPageSize());
        // 一级都可以看到
        if (!HeaderUtils.getUserLevel().equals("1")) {
            //审批人和发起人和接收组织可以看到
            if (org.apache.commons.lang3.StringUtils.isEmpty(taskQueryDTO.getRectificationUnit())) {
                taskQueryDTO.setRectificationUnit(String.valueOf(HeaderUtils.getUserGroupIds()));
            }
            taskQueryDTO.setAuditor(HeaderUtils.getUserId());
            taskQueryDTO.setReportUserId(HeaderUtils.getUserId());
        }

        return taskMapper.queryTaskInfoList(page, taskQueryDTO);
    }

    public TaskGetQueryDTO getTaskById(Integer taskId) {
        TaskGetQueryDTO taskGetQueryDTO = taskMapper.selectById(taskId);
        if (taskGetQueryDTO == null) {
            throw new CheckException("该任务不存在");
        }

        List<TaskProblemEntity> problemEntities = problemService.select(taskId);
        List<TaskProblemDTO> problemDTOs = problemEntities.stream().map(entity -> {
            TaskProblemDTO dto = new TaskProblemDTO();
            BeanUtils.copyProperties(entity, dto);
            return dto;
        }).collect(Collectors.toList());

        taskGetQueryDTO.setProblemList(problemDTOs);
        return taskGetQueryDTO;
    }

    //包含反馈信息
    public TaskGetDescQueryDTO getTaskAndProblemById(Integer taskId) {
        TaskGetQueryDTO taskGetQueryDTO = taskMapper.selectById(taskId);
        if (taskGetQueryDTO == null) {
            throw new CheckException("该任务不存在");
        }
        TaskGetDescQueryDTO taskGetDescQueryDTO = new TaskGetDescQueryDTO();
        BeanUtils.copyProperties(taskGetQueryDTO, taskGetDescQueryDTO);

        List<TaskProblemDescDTO> problemEntities = problemService.selectDesc(taskId, HeaderUtils.getUserId());

        taskGetDescQueryDTO.setProblemList(problemEntities);
        return taskGetDescQueryDTO;
    }


    public List<TaskStatusDTO> queryTaskStatus(Integer taskId) {
        TaskGetQueryDTO taskGetQueryDTO = taskMapper.selectById(taskId);
        if (taskGetQueryDTO == null) {
            throw new CheckException("该任务不存在");
        }
        //最终返回对象
        List<TaskStatusDTO> taskStatusDTOList = new ArrayList<>();
        //整改部门id列表
        List<Integer> groupIds = Arrays.stream(taskGetQueryDTO.getRfUnits().split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        List<Map<Integer, String>> groupNameByIds = groupService.getGroupNameByIds(groupIds);
        for (Integer groupId : groupIds) {
            TaskStatusDTO taskStatusDTO = new TaskStatusDTO();
            taskStatusDTO.setStatusAll(taskGetQueryDTO.getStatus());
            if (StringUtils.isIdInCommaString(taskGetQueryDTO.getReceiveUnits(), String.valueOf(groupId))) {
                taskStatusDTO.setStatus1("已接收");
            } else {
                taskStatusDTO.setStatus1("未接收");
            }
            if (StringUtils.isIdInCommaString(taskGetQueryDTO.getFbUnits(), String.valueOf(groupId))) {
                taskStatusDTO.setStatus2("已处理");
            } else {
                taskStatusDTO.setStatus2("未处理");
            }
            if (StringUtils.isIdInCommaString(taskGetQueryDTO.getRwUnits(), String.valueOf(groupId))) {
                taskStatusDTO.setStatus3("反馈通过");
            } else {
                taskStatusDTO.setStatus3("反馈未通过");
            }
            for (Map<Integer, String> idNameMap : groupNameByIds) {
                if (groupId.equals(idNameMap.get("groupId"))) {
                    taskStatusDTO.setGroupName(idNameMap.get("groupName"));
                    break;
                }
            }
            taskStatusDTOList.add(taskStatusDTO);
        }
        return taskStatusDTOList;
    }


    public List<TaskReportDTO> getData(TaskQueryReportDTO taskQueryDTO) {
        List<TaskReportDTO> report = taskMapper.getReport(taskQueryDTO);

        report.forEach(it -> {
            it.setNoCompleteds(it.getTotal() - it.getCompleteds());
        });
        return report;
    }

    public List<TaskReportDTO> getReport(TaskQueryReportDTO taskQueryDTO) {
        //// 一级都可以看到
        //if (!HeaderUtils.getUserLevel().equals("1")) {
        //    //审批人和发起人和接收组织可以看到
        //    if (taskQueryDTO.getRectificationUnit() == null) {
        //        taskQueryDTO.setRectificationUnit(String.valueOf(HeaderUtils.getUserGroupIds()));
        //    }
        //    taskQueryDTO.setAuditor(HeaderUtils.getUserId());
        //    taskQueryDTO.setReportUserId(HeaderUtils.getUserId());
        //}
        List<TaskReportDTO> report = taskMapper.getReport(taskQueryDTO);

        report.forEach(it -> {
            it.setNoCompleteds(it.getTotal() - it.getCompleteds());
        });
        // 把已有结果放入 Map，方便查找
        Map<String, TaskReportDTO> reportMap = report.stream()
                .collect(Collectors.toMap(
                        r -> r.getGroupName() + "_" + r.getProblemType(),
                        r -> r
                ));

        // 构建完整结果
        List<TaskReportDTO> fullReport = new ArrayList<>();

        for (OrgEnum org : OrgEnum.values()) {
            for (ProblemTypeEnum type : ProblemTypeEnum.values()) {
                String key = org.getName() + "_" + type.getLabel(); // 假设枚举里有 getDesc()

                TaskReportDTO dto = reportMap.getOrDefault(key, buildEmptyDTO(org, type));
                fullReport.add(dto);
            }
        }
        return fullReport;
    }

    private TaskReportDTO buildEmptyDTO(OrgEnum org, ProblemTypeEnum type) {
        TaskReportDTO dto = new TaskReportDTO();
        dto.setGroupName(org.getName());
        dto.setProblemType(type.getLabel());
        dto.setTotal(0);
        dto.setCompleteds(0);
        dto.setNoCompleteds(0);
        dto.setOverdues(0);
        return dto;
    }
}
